<?php

namespace App\Http\Controllers\Ajax;

use App\Handlers\SendSmsHandler;
use App\Http\Requests\BindPhoneRequest;
use App\Models\Userinfo;
use App\Models\WxuserMcard;
use App\Repositories\CardRepository;

class VerificationCodesController extends Controller
{
    protected $smsHandler;

    /**
     * VerificationCodesController constructor.
     * @param SendSmsHandler $smshandler
     */
    public function __construct(SendSmsHandler $smshandler)
    {
        $this->smsHandler = $smshandler;
    }

    /**
     * @param BindPhoneRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
     */
    public function store(BindPhoneRequest $request)
    {
        $mcard = WxuserMcard::where('id_merchant',session('web_merchant')->id_merchant)
                            ->where('member_optional_telephone',$request->telephone)
                            ->first();

        if($mcard) return $this->response->array(['code'=>405,'msg'=>'该手机号已被占用']);

        $code = mt_rand(1000,9999);

        $res = $this->smsHandler->send($request->get('telephone'),[
            'template' => 'SMS_129761234',
            'data' => [
                'trade' => $code
            ],
        ],$code);

        if(!$res) return $this->response->array(['code'=>500,'msg'=>'验证码发送失败']);

        return $this->response->array(['code'=>200,'msg'=>'验证码发送成功，请注意查收'.$code]);
    }

    /**
     * @param BindPhoneRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function validateCode(BindPhoneRequest $request,CardRepository $repository)
    {
        $phone = $request->get('telephone');
        $secret_param = $request->get('secret_param','');

        $res = $this->smsHandler->validateCode('SMS_129761234',$phone,$request->get('code'));

        if($res['code']!==200) return $this->response->array($res);

        /*$user = session('web_auth_user');*/

        /*$user_info = Userinfo::where('telephone',$phone)->first();*/

        /*if(empty($user_info)) $user_info = Userinfo::create(['telephone'=>$phone]);*/

        /*$user->id_userinfo = $user_info->id;
        $user->save();*/
        /*session(['web_user'=>$user]);*/

        //查询该手机号是否有会员卡没有就绑定默认卡 、、session('want_redirect_url','/')
        $res = $repository->createOrShowCard($phone,$secret_param);

        //if($secret_param) $repository->giveShareGiftBy($secret_param);

        return $this->response->array($res);
    }
}
